home *** CD-ROM | disk | FTP | other *** search
- Path: news.halcyon.com!usenet
- From: normanb@halcyon.com (Norm Bryar)
- Newsgroups: comp.lang.c++
- Subject: Re: Virtual Base Class
- Date: Tue, 12 Mar 1996 16:40:14 GMT
- Organization: Northwest Nexus Inc.
- Message-ID: <4i49c5$qtc@news.halcyon.com>
- References: <313F98D0.102E@ucla.edu> <4i1gnv$b7i@uuneo.neosoft.com>
- NNTP-Posting-Host: blv-pm3-ip12.halcyon.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- Wmatthew@lan-aces.com (W. Matthews) wrote:
-
- >In article <313F98D0.102E@ucla.edu>, Dennis Rahaman <dennisr@ucla.edu> says:
- >>
- >>This is what I want to do:
- >>
- >> a
- >> / \
- >> b c
- >> \ /
- >> d
- >>
- >>
- >>class b : public virtual a
- >> {
- >> //...
- >> };
- >>
- >>class c : public virtual b
- >> {
- >> //...
- >> };
- >>
- >>class d : public b, public c
- >> {
- >> //...
- >> };
- >>
- >>
- >>void f ()
- >> {
- >> a a1;
- >> d* pd = (d*) &a1; // error: can't cast virtual base to derived
- >> }
- >>
- >>///////////////////////////////////////////////////////////
- >>Can someone explain why I can't cast a virtual base class to a derived
- >>class?
- >>
- >>What should I do instead?
- >>
-
- If your compiler supports Run-Time Type Information (RTTI), enable it
- and use dynamic_cast<d *>(pa). If the cast cannot succeed (if d
- weren't really derived from a), it will return NULL, otherwise the
- cast succeeds. Down-casting to derived classes is otherwise extremely
- risky; you could be lying and telling the compiler to look the other
- way. Using dynamic_cast<> is best.
-
- --Norm
-
-
-
-